# -*- coding: utf-8 -*-
"""
收货地址服务层

负责处理收货地址相关的业务逻辑
"""
from typing import Optional, List, Dict, Any
from app.repositories.address_repository import AddressRepository


class AddressService:
    """收货地址服务类"""
    
    def __init__(self):
        self.address_repository = AddressRepository()
    
    def create_address(self, user_id: str, address_data: Dict[str, Any]) -> Dict[str, Any]:
        """创建收货地址"""
        try:
            # 验证必填字段
            required_fields = ['name', 'phone', 'province', 'city', 'district', 'detail']
            for field in required_fields:
                if not address_data.get(field):
                    raise ValueError(f"缺少必填字段: {field}")
            
            # 验证手机号格式
            if not self._validate_phone(address_data.get('phone')):
                raise ValueError("手机号格式不正确")
            
            # 验证性别
            if address_data.get('gender') and address_data['gender'] not in ['male', 'female']:
                raise ValueError("性别只能是 male 或 female")
            
            # 创建地址
            address = self.address_repository.create_address(user_id, address_data)
            
            if not address:
                raise ValueError("创建地址失败")
            
            return {
                "address_id": address.get('address_id'),
                "name": address.get('name'),
                "phone": address.get('phone'),
                "gender": address.get('gender'),
                "type": address.get('type'),
                "province": address.get('province'),
                "city": address.get('city'),
                "district": address.get('district'),
                "detail": address.get('detail'),
                "is_default": address.get('is_default'),
                "created_time": str(address.get('created_time')) if address.get('created_time') else None,
                "updated_time": str(address.get('updated_time')) if address.get('updated_time') else None
            }
            
        except Exception as e:
            raise Exception(f"创建地址失败: {str(e)}")
    
    def update_address(self, address_id: str, user_id: str, address_data: Dict[str, Any]) -> bool:
        """更新收货地址"""
        try:
            # 验证必填字段
            required_fields = ['name', 'phone', 'province', 'city', 'district', 'detail']
            for field in required_fields:
                if field in address_data and not address_data.get(field):
                    raise ValueError(f"字段不能为空: {field}")
            
            # 验证手机号格式
            if 'phone' in address_data and not self._validate_phone(address_data.get('phone')):
                raise ValueError("手机号格式不正确")
            
            # 验证性别
            if address_data.get('gender') and address_data['gender'] not in ['male', 'female']:
                raise ValueError("性别只能是 male 或 female")
            
            # 更新地址
            success = self.address_repository.update_address(address_id, user_id, address_data)
            
            if not success:
                raise ValueError("地址不存在或无权限操作")
            
            return True
            
        except Exception as e:
            raise Exception(f"更新地址失败: {str(e)}")
    
    def delete_address(self, address_id: str, user_id: str) -> bool:
        """删除收货地址"""
        try:
            success = self.address_repository.delete_address(address_id, user_id)
            
            if not success:
                raise ValueError("地址不存在或无权限操作")
            
            return True
            
        except Exception as e:
            raise Exception(f"删除地址失败: {str(e)}")
    
    def get_user_addresses(self, user_id: str) -> List[Dict[str, Any]]:
        """获取用户地址列表"""
        try:
            addresses = self.address_repository.find_user_addresses(user_id)
            
            # 转换数据格式
            result = []
            for address in addresses:
                result.append({
                    "address_id": address.get('address_id'),
                    "name": address.get('name'),
                    "phone": address.get('phone'),
                    "gender": address.get('gender'),
                    "type": address.get('type'),
                    "province": address.get('province'),
                    "city": address.get('city'),
                    "district": address.get('district'),
                    "detail": address.get('detail'),
                    "is_default": address.get('is_default', False),
                    "created_time": str(address.get('created_time')) if address.get('created_time') else None,
                    "updated_time": str(address.get('updated_time')) if address.get('updated_time') else None
                })
            
            return result
            
        except Exception as e:
            raise Exception(f"获取地址列表失败: {str(e)}")
    
    def get_address_detail(self, address_id: str, user_id: str) -> Optional[Dict[str, Any]]:
        """获取地址详情"""
        try:
            address = self.address_repository.find_address_by_id(address_id, user_id)
            
            if not address:
                return None
            
            return {
                "address_id": address.get('address_id'),
                "name": address.get('name'),
                "phone": address.get('phone'),
                "gender": address.get('gender'),
                "type": address.get('type'),
                "province": address.get('province'),
                "city": address.get('city'),
                "district": address.get('district'),
                "detail": address.get('detail'),
                "is_default": address.get('is_default', False),
                "created_time": str(address.get('created_time')) if address.get('created_time') else None,
                "updated_time": str(address.get('updated_time')) if address.get('updated_time') else None
            }
            
        except Exception as e:
            raise Exception(f"获取地址详情失败: {str(e)}")
    
    def set_default_address(self, address_id: str, user_id: str) -> bool:
        """设置默认地址"""
        try:
            success = self.address_repository.set_default_address(address_id, user_id)
            
            if not success:
                raise ValueError("地址不存在或无权限操作")
            
            return True
            
        except Exception as e:
            raise Exception(f"设置默认地址失败: {str(e)}")
    
    def get_default_address(self, user_id: str) -> Optional[Dict[str, Any]]:
        """获取默认地址"""
        try:
            addresses = self.get_user_addresses(user_id)
            
            for address in addresses:
                if address.get('is_default'):
                    return address
            
            return None
            
        except Exception as e:
            raise Exception(f"获取默认地址失败: {str(e)}")
    
    def _validate_phone(self, phone: str) -> bool:
        """验证手机号格式"""
        if not phone:
            return False
        
        # 简单的手机号验证（11位数字）
        return len(phone) == 11 and phone.isdigit()
    
    def get_address_statistics(self, user_id: str) -> Dict[str, Any]:
        """获取地址统计信息"""
        try:
            addresses = self.address_repository.find_user_addresses(user_id)
            
            total_count = len(addresses)
            default_count = sum(1 for addr in addresses if addr.get('is_default'))
            
            # 按类型分组统计
            type_stats = {}
            for address in addresses:
                addr_type = address.get('type', 'other')
                type_stats[addr_type] = type_stats.get(addr_type, 0) + 1
            
            # 按省份分组统计
            province_stats = {}
            for address in addresses:
                province = address.get('province', '未知')
                province_stats[province] = province_stats.get(province, 0) + 1
            
            # 转换为列表格式
            type_statistics = [
                {"type": type_name, "count": count}
                for type_name, count in type_stats.items()
            ]
            
            province_statistics = [
                {"province": province_name, "count": count}
                for province_name, count in province_stats.items()
            ]
            
            return {
                "total_addresses": total_count,
                "default_addresses": default_count,
                "has_default": default_count > 0,
                "type_statistics": type_statistics,
                "province_statistics": province_statistics
            }
            
        except Exception as e:
            raise Exception(f"获取地址统计失败: {str(e)}") 